package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.wemedia.WemediaConstants;
import com.heima.model.message.NewsAutoScanConstants;
import com.heima.model.message.NewsUpOrDownConstants;
import com.heima.model.message.PublishArticleConstants;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    String webSite;

    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //1.检查参数
        if (dto.getEnable() == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "状态或id不能为空");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        WmNews wmNews = getById(dto.getId());
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR, "状态不对");
        }
        wmNews.setEnable(dto.getEnable());
        updateById(wmNews);
        if (wmNews.getArticleId()!=null) {
            if(dto.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
                // 上架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,wmNews.getArticleId());
            }else {
                // 下架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,wmNews.getArticleId());
            }
        }
        //update(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId,dto.getId()));
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult delNews(Integer id) {
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数为空");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已发布，不能删除");
        }
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));

        removeById(id);

        return ResponseResult.okResult();
    }


    @Override
    public ResponseResult findWmNewsById(Integer id) {
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数为空");
        }
        WmNews byId = getById(id);
        if (byId == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ResponseResult result = ResponseResult.okResult(byId);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //参数校验
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数为空");
        }
        dto.checkParam();
        //判断是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaQuery();
        //模糊查询
        wrapper.like(StringUtils.isNotBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword());
        //时间查询
        wrapper.ge(dto.getBeginPubDate() != null, WmNews::getPublishTime, dto.getBeginPubDate());
        wrapper.le(dto.getEndPubDate() != null, WmNews::getPublishTime, dto.getEndPubDate());
        // 文章状态
        wrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());

        wrapper.eq(WmNews::getUserId, user.getId());
        //根据创建时间排序
        wrapper.orderByDesc(WmNews::getCreatedTime);
        //分页查询
        Page<WmNews> wmNewsPage = new Page<>(dto.getPage(), dto.getSize());

        page(wmNewsPage, wrapper);

        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), wmNewsPage.getTotal());
        result.setData(wmNewsPage.getRecords());
        // 处理文章图片
        result.setHost(webSite);
        return result;
    }

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult submitNews(WmNewsDTO dto) {
        // 1 参数校验
        if (StringUtils.isBlank(dto.getContent()) || StringUtils.isBlank(dto.getTitle())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章标题 或 内容 不能为空");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //属性拷贝
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //如果文章布局是自动，需要设置为null
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        // 如果是草稿  直接返回
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(dto.getStatus())) {
            saveWmNews(wmNews);
            return ResponseResult.okResult();
        }
        //解析图片
        List<String> images = dto.getImages();
        if (!CollectionUtils.isEmpty(images)) {
            wmNews.setImages(imageListToStr(images));
        }
        //保存
        wmNews.setUserId(user.getId());
        saveWmNews(wmNews);
        //  3.1 抽取文章中关联的图片路径
        String content = dto.getContent();
        //3.1 抽取文章中关联的图片路径
        List<String> urlList = parseContentImages(content);

        //  3.2 关联文章内容中的图片和素材关系
        if (!CollectionUtils.isEmpty(urlList)) {
            saveRelativeInfo(urlList, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
        }
        // 3.3 关联文章封面中的图片和素材关系  封面可能是选择自动或者是无图
        saveRelativeInfoForCover(urlList, wmNews, dto);
        // 3.4 发送待审核消息
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());
        log.info("成功发送待审核消息，待审核的文章id为: {}", wmNews.getId());
        return ResponseResult.okResult();


    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;


    private void saveRelativeInfoForCover(List<String> urlList, WmNews wmNews, WmNewsDTO dto) {

        // 1. 获取dto中 传入的封面集合
        List<String> images = dto.getImages();
        // 2. 判断dto中的type属性是否为 -1
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            //     2.1  如果是-1  需要自动生成封面
            //     2.2  根据内容中素材列表生成封面
            int size = urlList.size();
            if (size > 0 && size <= 2) {
                //         如果内容素材数量大于 0   小于 等于2   生成单图封面
                images = urlList.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else if (size > 2) {
                //         如果内容素材数量大于 0   大于  2   生成多图封面
                images = urlList.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else {
                //         如果内容素材数量为 0      生成无图封面
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            //         重新修改wmNews
            if (!CollectionUtils.isEmpty(images)) {
                wmNews.setImages(imageListToStr(images));
            }
            updateById(wmNews);
        }
        // 3. 批量保存 封面 和 素材的关联关系
        if (!CollectionUtils.isEmpty(images)) {
            // 如果封面不是自动生成的，是前端直接传过来的 会有前缀路径 记得替换掉
            images = images.stream().map(url -> url.replaceAll(webSite, "")).collect(Collectors.toList());
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_IMAGE_REFERENCE);
        }

    }

    @Autowired
    WmMaterialMapper wmMaterialMapper;

    public void saveRelativeInfo(List<String> urlList, Integer newsId, Short type) {
        // 1. 根据素材路径url集合   查询出对应的素材id列表
//        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
//                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
//                .in(WmMaterial::getUrl, urlList)
//                .select(WmMaterial::getId)
//        );
        List<Integer> ids = wmMaterialMapper.selectRelationsIds(urlList, WmThreadLocalUtils.getUser().getId());
        // 2. 判断 id列表  长度  是否小于 素材列表长度  如果小于 说明缺失素材
        if (CollectionUtils.isEmpty(ids) || ids.size() < urlList.size()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "素材缺失，保存关联关系失败");
        }
        // 3. 根据id列表  newsId  type  保存关联关系 到 wm_news_material
        wmNewsMaterialMapper.saveRelations(ids, newsId, type);
//        for (WmMaterial wmMaterial : wmMaterials) {
//            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
//            wmNewsMaterial.setMaterialId(wmMaterial.getId());
//            wmNewsMaterial.setNewsId(newsId);
//            wmNewsMaterial.setType(type);
//            wmNewsMaterialMapper.insert(wmNewsMaterial);
//        }
    }

    private List<String> parseContentImages(String content) {
        List<Map> contents = JSON.parseArray(content, Map.class);
        // 遍历文章内容   将所有 type为image的 value获取出来  去除前缀路径
        return contents.stream()
                // 过滤type=image所有的集合
                .filter(map -> map.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE))
                // 获取到image下的value  图片url
                .map(x -> (String) x.get("value"))
                // 图片url去除前缀
                .map(url -> url.replace(webSite, "").replace(" ", ""))
                // 去除重复的路径
                .distinct()
                // stream 转成list集合
                .collect(Collectors.toList());
    }


    /**
     * 保存或修改文章
     *
     * @param wmNews 文章对象（前端传递）
     */
    private void saveWmNews(WmNews wmNews) {
        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP); // 上架
        if (wmNews.getId() == null) { // 保存操作
            save(wmNews);
        } else {  // 修改
            // 当前文章 和 素材关系表数据删除
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }
    }

    private String imageListToStr(List<String> images) {
        return images.stream().map(url -> url.replace(webSite, ""))
                .collect(Collectors.joining(","));

    }

    @Autowired
    WmNewsMapper wmNewsMapper;

    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //参数校验
        dto.checkParam();
        //参数设置
        dto.setPage((dto.getPage() - 1) * dto.getSize());
        /*if (dto.getTitle() != null && dto.getTitle() != "") {
            dto.setTitle("%" + dto.getTitle() + "%");
        }*/
        //分页查询
        List<WmNewsVO> listAndPage = wmNewsMapper.findListAndPage(dto);

        if (listAndPage == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //统计条数
        Long count = wmNewsMapper.findListCount(dto);
        //封装返回值
        PageResponseResult pageRes = new PageResponseResult(dto.getPage(), dto.getSize(), count, listAndPage);
        pageRes.setHost(webSite);
        return pageRes;
    }

    @Autowired
    WmUserMapper wmUserMapper;

    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //创建返回值对象
        WmNewsVO wmNewsVO = new WmNewsVO();
        //属性拷贝
        BeanUtils.copyProperties(wmNews, wmNewsVO);
        //查询作者信息(返回值里面有作者姓名信息)
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser.getName()!=null) {
            wmNewsVO.setAuthorName(wmUser.getName());
        }else {
            wmNewsVO.setAuthorName(null);
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVO);
        responseResult.setHost(webSite);
        return responseResult;
    }

    @Override
    public ResponseResult updateStatus(NewsAuthDTO dto) {
        //参数校验
        if (dto==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取文章对象
        WmNews wmNews = getById(dto.getId());
        //判断文章是否为空和状态是否为3
        if(wmNews==null && wmNews.getStatus().equals(WmNews.Status.ADMIN_AUTH.getCode())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //审核失败2
        if(dto.getStatus().equals(WmNews.Status.FAIL.getCode())){
            wmNews.setReason("人工审核不通过:"+dto.getMsg());
        }
        //修改当前状态
        wmNews.setStatus(dto.getStatus());
        updateById(wmNews);
        if(dto.getStatus().equals(WmNews.Status.ADMIN_SUCCESS.getCode())) {
            // 发布时间
            long publishTime = wmNews.getPublishTime().getTime();
            // 当前时间
            long nowTime = new Date().getTime();
            long remainTime = publishTime - nowTime;
            // 发布文章
            rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                    , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                    , wmNews.getId()
                    , message -> {                              // 延时消息 必设置
                        message.getMessageProperties().setHeader("x-delay", remainTime <= 0 ? 0 : remainTime);
                        return message;
                    }
            );
        }
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());
        return ResponseResult.okResult();
    }
}
